<template>
    <div class="login">
        <el-card class="box-card">
            <!-- 通过ref获得相应form对象进行下一步跳转 -->
            <el-form ref="form" :rules="rules" :model="formInline" class="demo-form-inline">
                <!-- prop对应rules内字段 -->
                <el-form-item prop="user" label="用户名">
                    <el-input v-model="formInline.user" placeholder="请输入用户名" />
                </el-form-item>
                <el-form-item prop="password" label="密码">
                    <el-input v-model="formInline.password" placeholder="请输入密码" type="password" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">登录</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>
    

<script setup lang='ts'>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { FormItemRule, FormInstance, ElMessage } from 'element-plus'

type From = {
    user: string,
    password: string
}
type Rules = {
    // 对象化
    [K in keyof From]?: Array<FormItemRule>
}
const router = useRouter()
const formInline = reactive<From>({
    user: '',
    password: '',
})
const form = ref<FormInstance>()
const rules = reactive<Rules>({
    user: [
        {
            required: true,
            message: "请输入账号",
            type: "string",
        }
    ],
    password: [
        {
            required: true,
            message: "请输入密码",
            type: "string",
        }
    ]
})

const onSubmit = () => {
    //true false 表示是否通过rules
    form.value?.validate((validate) => {
        if (validate) {
            localStorage.setItem('token', '1')
            router.push('/X2')
        } else {
            ElMessage.error("字段不完整")

        }
    })
}

//  模拟后端数据 
/* route: [
    {
        path: "/demo1",
        name: "Demo1",
        component: "demo1.vue"
    },
    {
        path: "/demo2",
        name: "Demo2",
        component: "demo2. vue"
    }
] */
import { axios } from '../../server/axios';
type X = {
    data: {
        route: [{
            path: string,
            name: string,
            component: string
        }]
    }
}
const initRouter = async () => {
    const result: X = await axios.get('http://localhost:9999/login', { params: formInline })
    result.data.route.forEach((v: any) => {
        router.addRoute({
            path: v.path,
            name: v.name,
            component: () => import(`../views/${v.component}`)
        })
    })
    router.push('/index')
    console.log(router.getRoutes());
}

</script>

<style scoped lang="scss"></style>